package com.tianquan.exception;

import com.tianquan.log.Log;
import com.tianquan.log.Task;
import com.tianquan.log.ThreadLocalContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Date;

import static com.tianquan.log.Task.LOCK;
import static com.tianquan.log.Task.list;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(BaseException.class)
    public String handleErrorException(BaseException exception) {
        if (ThreadLocalContext.getUserId() == null) return exception.getMsg();
        // 将异常信息记录到数据库
        LogToDatabase(exception);
        return exception.getMsg();
    }

    private void LogToDatabase(BaseException exception) {
        Log log = new Log();
        log.setUser_id(ThreadLocalContext.getUserId());
        log.setLevel(exception.getLevel());
        log.setIp(ThreadLocalContext.getIp());
        log.setModule(ThreadLocalContext.getPath().split("/")[1]);
        log.setUrl(ThreadLocalContext.getPath());
        log.setMessage(exception.toString());
        log.setCreate_time(new Date());
        Task.executorService.submit(new Thread(() -> {
            LOCK.lock();
            list.add(log);
            LOCK.unlock();
        }));
    }


    /**
     * 处理其他未知异常。
     * 返回HTTP响应状态码500，包含错误代码和异常堆栈信息。
     *
     * @param exception 未知异常
     * @return 响应数据，包含错误代码和异常堆栈信息
     */
    @ExceptionHandler(Exception.class)
    public String handleUnknownException(Exception exception) {
        exception.printStackTrace();

        return exception.getMessage();
    }

}
